package com.sukumar.android.taxi;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Editable;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class AutoTaxtFareCalculatorActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.auto_taxi_fare_layout);
		final Button btnCalcFare = (Button) findViewById(R.id.calcFare);
		btnCalcFare.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Context context = getApplicationContext();

				EditText editxtMeterReading = (EditText) findViewById(R.id.meterReading);
				Editable ediMeterReading = (Editable) editxtMeterReading
						.getText();
				RadioGroup rgAutotaxiInd = (RadioGroup) findViewById(R.id.autoTaxiInd);
				CheckBox chkNightInd = (CheckBox) findViewById(R.id.nightInd);
				TextView tvDisplayFare = (TextView) findViewById(R.id.outputFare);

				StringBuffer sbFare = new StringBuffer();
				String strMeterReading = ediMeterReading.toString();
				Double dblMeterReading = new Double(0);
				boolean bErrFlag = false;

				if (strMeterReading.length() == 0) {
					bErrFlag = true;

					CharSequence error = getResources().getText(
							R.string.Error_Null);
					int duration = Toast.LENGTH_SHORT;
					Toast toast = Toast.makeText(context, error, duration);
					toast.setGravity(Gravity.CENTER_VERTICAL
							| Gravity.CENTER_HORIZONTAL, 0, 0);
					toast.show();
				} else {
					dblMeterReading = Double.parseDouble(strMeterReading);

					if (getNumberOfDecimalPlace(dblMeterReading) > 1) {
						bErrFlag = true;

						CharSequence error = getResources().getText(
								R.string.Error_Precision);
						int duration = Toast.LENGTH_SHORT;
						Toast toast = Toast.makeText(context, error, duration);
						toast.setGravity(Gravity.CENTER_VERTICAL
								| Gravity.CENTER_HORIZONTAL, 0, 0);
						toast.show();
					}
				}
				if (!bErrFlag) {
					int numAutoTaxiInd = rgAutotaxiInd
							.getCheckedRadioButtonId();
					boolean blNightInd = chkNightInd.isChecked();
					Double dblCalculatedFare = new Double(0.0);
					NumberFormat nf = new DecimalFormat("###,###.00");
					String strAutoTaxiText = "";

					if (numAutoTaxiInd == R.id.auto) {
						strAutoTaxiText = "Fare for Auto";
						dblCalculatedFare = calculateAutoFare(dblMeterReading);
					} else {
						strAutoTaxiText = "Fare for Taxi";
						dblCalculatedFare = calculateTaxiFare(dblMeterReading);
					}

					sbFare.append(strAutoTaxiText).append(": Rs ")
							.append(nf.format(dblCalculatedFare)).append("\n");

					if (blNightInd) {
						dblCalculatedFare = applyNightCharge(dblCalculatedFare,
								numAutoTaxiInd);
						sbFare.append(strAutoTaxiText)
								.append(" with night-charge: Rs ")
								.append(nf.format(dblCalculatedFare));
					}

					sbFare.trimToSize();
					tvDisplayFare.setText(sbFare.toString());
				} else {
					sbFare.delete(0, sbFare.length());
					tvDisplayFare.setText(sbFare.toString());
				}
			}
		});
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	private Double calculateAutoFare(Double pReading) {
		Double dblFare = new Double(0);
		if (pReading != null) {
			dblFare = pReading * 13 - 2;
		}
		return round(dblFare, 1);
	}

	private Double calculateTaxiFare(Double pReading) {
		Double dblFare = new Double(0);
		if (pReading != null) {
			dblFare = (((pReading - 1) / 6) * 100) + 16;
		}
		return round(dblFare, 2);
	}

	private Double applyNightCharge(Double pDblFare, int pAutotaxiInd) {
		Double dblRetVal = pDblFare * 1.25;
		if (pAutotaxiInd == R.id.auto) {
			return round(dblRetVal, 1);
		} else {
			return round(dblRetVal, 2);
		}
	}

	private Double round(Double pDblFare, int pDivisor) {
		BigDecimal bdDivisor = new BigDecimal(pDivisor);
		BigDecimal bdAmount = new BigDecimal(pDblFare);

		BigDecimal result = new BigDecimal(bdAmount.multiply(bdDivisor)
				.add(new BigDecimal(".5")).toBigInteger()).divide(bdDivisor);
		return result.doubleValue();
	}

	private Integer getNumberOfDecimalPlace(Double value) {
		final BigDecimal bigDecimal = new BigDecimal("" + value);
		final String s = bigDecimal.toPlainString();
		final Integer index = s.indexOf('.');
		if (index < 0) {
			return 0;
		}
		return s.length() - 1 - index;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.about_menu, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		final CharSequence[] items = { "Usage", "Change Log", "About" };
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Info");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				Intent myIntent = new Intent(getApplicationContext(),
						AutotaxiAboutActivity.class);
				myIntent.putExtra("selected", item);
				startActivity(myIntent);
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
		return super.onMenuItemSelected(featureId, item);
	}
}